<script setup>
import { RouterLink, RouterView } from 'vue-router'
import { ref, onMounted } from 'vue'

// 登录状态
const isLoggedIn = ref(false)
const currentUser = ref('')

// 检查登录状态
onMounted(() => {
  checkLoginStatus()
})

const checkLoginStatus = () => {
  const loggedIn = localStorage.getItem('isLoggedIn') || sessionStorage.getItem('isLoggedIn')
  if (loggedIn) {
    isLoggedIn.value = true
    currentUser.value = localStorage.getItem('username') || sessionStorage.getItem('username')
  }
}

// 处理登出
const handleLogout = () => {
  localStorage.removeItem('isLoggedIn')
  localStorage.removeItem('username')
  sessionStorage.removeItem('isLoggedIn')
  sessionStorage.removeItem('username')
  isLoggedIn.value = false
  currentUser.value = ''
}
</script>

<template>
  <header>
    <div class="wrapper">
      <nav>
        <RouterLink to="/">首页</RouterLink>
        <RouterLink to="/about">关于</RouterLink>
        <RouterLink to="/mall">商城</RouterLink>
        <RouterLink to="/payment">支付</RouterLink>
        <RouterLink v-if="!isLoggedIn" to="/login">登录</RouterLink>
        <span v-else class="user-info">
          {{ currentUser }} | 
          <button @click="handleLogout" class="logout-btn">登出</button>
        </span>
      </nav>
    </div>
  </header>

  <RouterView />
</template>

<style scoped>
header {
  line-height: 1.5;
  max-height: 100vh;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

nav {
  width: 100%;
  font-size: 12px;
  text-align: center;
  margin-top: 2rem;
}

nav a.router-link-exact-active {
  color: var(--color-text);
}

nav a.router-link-exact-active:hover {
  background-color: transparent;
}

nav a {
  display: inline-block;
  margin: 0 1rem;
  border: 1px solid transparent;
  border-left: 1px solid var(--color-border);
  border-radius: 2px;
  padding: 0.5rem 1rem;
  transition: background-color 0.2s;
}

nav a:hover {
  background-color: var(--color-background-soft);
}

.user-info {
  display: inline-block;
  margin: 0 1rem;
  color: var(--color-text);
}

.logout-btn {
  background: none;
  border: none;
  color: var(--color-primary);
  cursor: pointer;
  text-decoration: underline;
  padding: 0;
  font: inherit;
}

nav a:first-of-type {
  border: 0;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }

  nav {
    text-align: left;
    margin-left: -1rem;
    font-size: 1rem;

    padding: 1rem 0;
    margin-top: 1rem;
  }
}
</style>
